<template>
  <div>
    <a-card class="card" title="销售订单信息">
      <a-form :form="form">
        <a-form-item v-show="false"><a-input v-decorator="['id']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['code']" /></a-form-item>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="公司名称">
              <a-select style="width: 100%" placeholder="请选择公司名称" v-decorator="['companyId', {rules: [{ required: true, message: '请选择公司名称' }]}]">
                <a-select-option v-for="(item,index) in companyData" :key="index" :value="item.id">{{ item.fullName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
            <a-form-item label="客户名称">
              <a-auto-complete
                allow-clear
                style="width: 100%"
                placeholder="请选择客户名称"
                v-decorator="['customerId',{rules: [{ required: true, message: '请选择客户名称'}]}]"
                @search="onSearchCustomer"
                @select="onSelectCustomer"
                @change="onChangeCustomer">
                <template slot="dataSource">
                  <a-select-option v-for="item in customerData" :key="item.id" :title="item.name">
                    {{ item.name }}
                  </a-select-option>
                </template>
              </a-auto-complete>
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
            <a-form-item
              label="签订地">
              <a-input style="width: 100%" v-decorator="['signPlace',{rules: [{ required: true, message: '请填写签订地'}]}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              label="签订时间">
              <a-date-picker style="width: 100%" v-decorator="['signDate',{rules: [{ required: true, message: '请选择签订时间'}]}]"/>
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
            <a-form-item
              label="联系人">
              <a-input style="width: 100%" v-decorator="['contacts',{rules: [{ required: false, message: '请填写联系人'}]}]"/>
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
            <a-form-item
              label="联系方式">
              <a-input style="width: 100%" v-decorator="['tel',{rules: [{ required: false, message: '请填写联系方式'}]}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              label="交付时间">
              <a-date-picker style="width: 100%" :disabled-date="disabledDate" v-decorator="['deliveryTime',{rules: [{ required: false, message: '请选择交付时间'}]}]"/>
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
            <a-form-item
              label="交付地址">
              <a-input style="width: 100%" v-decorator="['deliveryAddress',{rules: [{ required: false, message: '请填写交付地址'}]}]"/>
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
            <a-form-item
              label="税率">
              <a-select style="width: 100%" placeholder="请选择税率" v-decorator="['taxRate', {rules: [{ required: true, message: '请选择税率' }]}]" @change="changeTaxRate">
                <a-select-option v-for="(item,index) in taxRateData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col>
            <a-form-item
              label="备注">
              <a-textarea placeholder="请输入备注" v-decorator="['remark']"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card class="card" title="订单明细">
      <a-table
        :columns="itemColumns"
        :dataSource="itemData"
        bordered
        size="small"
        :pagination="false"
        :scroll="{x: 1000}"
      >
        <template v-for="col in customRenderList" v-slot:[col]="text, record">
          <div :key="col">
            <a-form-item :validate-status="getFiledStatus(record.key, col)" style="margin-bottom: 0px">
              <a-input
                :read-only="readonlyArr.includes(col)"
                placeholder="请输入"
                v-if="record.editable && inputScopedSlots.includes(col)"
                :value="text"
                @change="e => handleChangeItem(e.target.value, record.key, col)"
              />
              <a-input
                :read-only="readonlyArr.includes(col)"
                placeholder="请输入"
                v-else-if="record.editable && col==='materialCode'"
                :value="text"
                @click="handleMaterialOpen(record)"
                @change="e => handleChangeItem(e.target.value, record.key, col)"
              />
              <!-- <a-select
                placeholder="请选择"
                style="display: block;"
                v-else-if="record.editable && selectScopedSlots.includes(col)"
                :value="text"
                @change="onChangeSelectItem($event, record.key, col)"
              >
                <a-select-option value="lucy">Lucy</a-select-option>
                <a-select-option value="jack">Jack</a-select-option>
              </a-select> -->
              <span v-else>{{ text }}</span>
            </a-form-item>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record">
          <span>
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus" @click="newItem">新增物料</a-button>
      <select-material ref="selectMaterial" :selected-rows-data="selectedMaterialRowsData" :selected-row-keys-data="selectedMatetialRowKeysData" :select-type="selectType" @sure="handleMaterialSure" />
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
      <!-- <div style="display: inline-block;padding: 0 20px;">
        <span style="font-weight: bold;font-size: 14px;">总计：</span>
        <span style="font-weight: bold;font-size: 14px;color: #40a9ff;"><span>{{ totalPrice }} * {{ taxRate }} = </span></span>
        <span style="font-weight: bold;font-size: 18px;color: red;"><span>￥ {{ totalTaxPrice }}</span></span>
      </div> -->
      <div style="display: inline-block;padding: 0 20px;">
        <span style="font-weight: bold;font-size: 14px;">含税总额：</span>
        <span style="font-weight: bold;font-size: 18px;color: red;"><span>￥ {{ totalTaxPrice }}</span></span>
        <span style="font-weight: bold;font-size: 14px;color: #40a9ff;"><span> ({{ totalPrice }} * {{ taxRate }})</span></span>
      </div>
      <a-button class="subButton" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import FooterToolBar from '@/components/FooterToolbar'
import moment from 'moment'
import { customerPage } from '@/api/modular/main/base/customer/customerManage'
import { saleOrderEdit, saleOrderDetail } from '@/api/modular/main/order/sale/saleOrderManage'
import selectMaterial from '@/components/bizComponents/selectMaterial.vue'
import BigNumber from 'bignumber.js'
import { validatePrice, validateNum } from '@/utils/validate'
import { companyList } from '@/api/modular/main/base/company/companyManage'
export default {
  components: {
    moment,
    BigNumber,
    FooterToolBar,
    selectMaterial
  },
  data () {
    return {
      code: '',
      loading: false,
      customerData: [],
      companyData: [],
      taxRateData: [],
      selectCustomerValue: '',
      itemData: [],
      // 每一列的插槽名 - 表格行内编辑用
      customRenderList: ['materialCode', 'materialName', 'materialModel', 'unitPrice', 'qty', 'unit', 'amount', 'deliveryDate'],
      // 用来匹配插槽中显示input框
      inputScopedSlots: ['unitPrice', 'qty', 'deliveryDate'],
      // 用来匹配插槽中显示select框
      selectScopedSlots: [],
      // 对于某些自动赋值的input框设为 只读
      readonlyArr: ['materialName', 'materialModel', 'unit', 'amount'],
      // 需要验证的字段
      needValidItemFields: ['materialCode', 'unitPrice', 'qty'],
      form: this.$form.createForm(this),
      selectedMaterialRowsData: [],
      selectedMatetialRowKeysData: [],
      selectType: 'checkbox',
      selectedItemKey: '',
      totalPrice: '0.00',
      totalTaxPrice: '0.00',
      taxRate: 1.0,
      itemColumns: [
        {
          title: '物料编码',
          dataIndex: 'materialCode',
          align: 'center',
          width: 200,
          scopedSlots: { customRender: 'materialCode' }
        },
        // {
        //   title: '物料名称',
        //   dataIndex: 'materialName',
        //   align: 'center',
        //   width: 200,
        //   scopedSlots: { customRender: 'materialName' }
        // },
        {
          title: '物料型号',
          dataIndex: 'materialModel',
          align: 'center',
          width: 300,
          scopedSlots: { customRender: 'materialModel' }
        },
        {
          title: '单价(￥)',
          dataIndex: 'unitPrice',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'unitPrice' }
        },
        {
          title: '数量',
          dataIndex: 'qty',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'qty' }
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'center',
          width: 80,
          scopedSlots: { customRender: 'unit' }
        },
        {
          title: '小计(￥)',
          dataIndex: 'amount',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'amount' }
        },
        {
          title: '货期',
          dataIndex: 'deliveryDate',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'deliveryDate' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 80,
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  created () {
    this.newItem()
    // 加载数据
    this.searchCustomer()
    this.searchCompany()
    const taxRateOption = this.$options
    this.taxRateData = taxRateOption.filters['dictData']('tax_rate')
    setTimeout(() => {
      this.form.setFieldsValue(
        {
          signDate: moment(this.getCurrentData(), 'YYYY-MM-DD')
        }
      )
    }, 100)
  },
  activated () {
    const oldCode = this.code
    this.code = this.$route.query.code
    if (oldCode !== this.code) {
      saleOrderDetail(this.code).then((res) => {
        if (res.success) {
          this.edit(res.data)
        } else {
          this.$message.error('数据加载失败:' + res.message)
        }
      })
    }
  },
  methods: {
    moment,
    getCurrentData() {
      return new Date().toLocaleDateString()
    },
    // 初始化方法
    edit (record) {
      // console.log(record)
      this.form.setFieldsValue(
        {
          id: this.$praseStrEmpty(record.id),
          code: this.$praseStrEmpty(record.code),
          companyId: this.$praseStrEmpty(record.companyId),
          customerId: this.$praseStrEmpty(record.customerId),
          signPlace: this.$praseStrEmpty(record.signPlace),
          signDate: moment(this.$praseStrEmpty(record.signDate), 'YYYY-MM-DD'),
          deliveryTime: moment(this.$praseStrEmpty(record.deliveryTime), 'YYYY-MM-DD'),
          deliveryAddress: this.$praseStrEmpty(record.deliveryAddress),
          contacts: this.$praseStrEmpty(record.contacts),
          tel: this.$praseStrEmpty(record.tel),
          taxRate: record.taxRate + '',
          remark: this.$praseStrEmpty(record.remark)
        }
      )
      this.selectCustomerValue = this.$praseStrEmpty(record.customerId)
      this.totalPrice = record.totalPrice
      this.totalTaxPrice = record.totalTaxPrice
      this.taxRate = 1 + (record.taxRate / 100.0)

      this.itemData = []
      let idx = 0
      for (const item of record.itemList) {
        this.itemData.push({
          key: (++idx).toString(),
          materialCode: item.materialCode,
          materialName: item.materialName,
          materialModel: item.materialModel,
          unitPrice: item.unitPrice,
          qty: item.qty,
          unit: item.unit,
          amount: item.amount,
          deliveryDate: item.deliveryDate,
          selectedRowKeysData: [ item.materialCode ],
          editable: true,
          isNew: true,
          validateStatus: []
        })
      }
    },
    handleMaterialOpen (record) {
      this.selectedItemKey = record.key
      this.selectType = 'radio'
      // 设置已选明细物料信息
      this.selectedMaterialRowsData = []
      this.selectedMatetialRowKeysData = []
      this.selectedMatetialRowKeysData.push(record['materialCode'])
      this.$refs.selectMaterial.add()
    },
    handleMaterialSure (selectedMaterialRowsData, selectedMatetialRowKeysData) {
      const newData = [...this.itemData]
      const checkMaterial = newData.find(item => selectedMaterialRowsData[0].code === item.materialCode)
      if (checkMaterial && checkMaterial.key !== this.selectedItemKey) {
        this.$message.error('物料[' + selectedMaterialRowsData[0].code + ']已存在，请选择其他物料')
      } else {
        const target = newData.find(item => this.selectedItemKey === item.key)
        if (target) {
          target['materialCode'] = selectedMaterialRowsData[0].code
          target['materialName'] = selectedMaterialRowsData[0].name
          target['materialModel'] = selectedMaterialRowsData[0].model
          target['unit'] = selectedMaterialRowsData[0].unit
          target['selectedRowKeysData'] = selectedMatetialRowKeysData
          this.itemData = newData
          this.validateItemField(this.selectedItemKey, 'materialCode', target['materialCode'])
        }
      }
    },
    searchCompany() {
      companyList({}).then((res) => {
        this.companyData = res.data
      })
    },
    searchCustomer(key) {
      customerPage({ 'name': key }).then((res) => {
         this.customerData = res.data.rows
      })
    },
    disabledDate(current) {
      return current && current < moment().endOf('day')
    },
    onSearchCustomer(searchText) {
      this.searchCustomer(searchText)
    },
    onSelectCustomer(value) {
      this.selectCustomerValue = value
    },
    onChangeCustomer(value) {
      this.selectCustomerValue = ''
    },
    newItem () {
      const length = this.itemData.length
      this.itemData.push({
        key: length === 0 ? '1' : (parseInt(this.itemData[length - 1].key) + 1).toString(),
        id: '',
        materialCode: '',
        materialName: '',
        materialModel: '',
        unitPrice: '',
        qty: '',
        unit: '',
        amount: '0.00',
        deliveryDate: '现货',
        selectedRowKeysData: [],
        editable: true,
        isNew: true,
        validateStatus: []
      })
    },
    remove (key) {
      const newData = this.itemData.filter(item => item.key !== key)
      this.itemData = newData
      this.countOrderPrice()
    },
    getRowByKey (key, newData) {
      const data = this.itemData
      return (newData || data).find(item => item.key === key)
    },
    changeTaxRate (value) {
      this.taxRate = 1 + (value / 100.0)
      this.countOrderPrice()
    },
    handleChangeItem (value, key, colName) {
      const newData = [...this.itemData]
      const target = newData.find(item => key === item.key)
      if (target) {
        target[colName] = value
        this.itemData = newData
      }
      this.validateItemField(key, colName, value)
      //  小计
      if (colName === 'unitPrice' || colName === 'qty') {
        if (target['unitPrice'] !== null && target['qty'] !== null && target['unitPrice'] !== '' && target['qty'] !== '') {
          target['amount'] = BigNumber(target['unitPrice']).times(BigNumber(target['qty'])).toFixed(2)
          this.countOrderPrice()
        }
      }
    },
    // onChangeSelectItem (value, rowKey, colName) {
    //   const newData = [...this.itemData]
    //   const target = newData.filter(item => rowKey === item.key)[0]
    //   if (target) {
    //     target[colName] = value
    //     // 根据select框的值自动带出某个input的值 - 因为第三列列名为materialName
    //     value === 'lucy' ? target.materialName = '根据lucy带出的值' : target.materialName = '根据jack带出的值'
    //     this.itemData = newData
    //   }
    // },
    getFiledStatus (key, col) {
      const target = this.itemData.find(item => key === item.key)
      if (target) {
        const statusObj = target['validateStatus'].find(item => col === item.col)
        if (statusObj) {
          return statusObj['status']
        }
      }
      return 'success'
    },
    setFiledStatus (key, col, error) {
      const status = error ? 'error' : 'success'
      const newData = [...this.itemData]
      const target = newData.find(item => key === item.key)
      if (target) {
        const statusObj = target['validateStatus'].find(item => col === item.col)
        if (statusObj) {
          statusObj['col'] = col
          statusObj['status'] = status
        } else {
          target['validateStatus'].push({
            col: col,
            validateStatus: status
          })
        }
        this.itemData = newData
      }
    },
    countOrderPrice () {
      var total = BigNumber(0)
      for (var data of this.itemData) {
        total = total.plus(BigNumber(data.amount))
      }
      this.totalPrice = total
      this.totalTaxPrice = total.times(BigNumber(this.taxRate)).toFixed(2)
    },
    validateItemField (key, col, value) {
      if (col === 'materialCode') {
        this.setFiledStatus(key, col, false)
        if (value === null || value === '') {
            this.setFiledStatus(key, col, true)
            return false
        }
      }
      if (col === 'unitPrice') {
        this.setFiledStatus(key, col, false)
        if (value === null || value === '' || !validatePrice(value)) {
            this.setFiledStatus(key, col, true)
            return false
        }
      }
      if (col === 'qty') {
        this.setFiledStatus(key, col, false)
        if (value === null || value === '' || !(validateNum(value).result)) {
            this.setFiledStatus(key, col, true)
            return false
        }
      }
      return true
    },
    filterEmptyItem () {
      const emptyKeys = []
      for (var data of this.itemData) {
        var key = data.key
        let allEmpty = true
        for (var field of this.needValidItemFields) {
          if (data[field] !== null && data[field] !== '') {
            allEmpty = false
          }
        }
        if (allEmpty) {
          emptyKeys.push(key)
        }
      }
      // 全空则直接删除该条数据
      if (emptyKeys.length > 0) {
        if (emptyKeys.length === this.itemData.length) {
          emptyKeys.splice(0, 1)
        }
        this.itemData = this.itemData.filter(item => !emptyKeys.includes(item.key))
      }
    },
    validateAllItemFields () {
      this.filterEmptyItem()
      if (this.itemData === null || this.itemData.length === 0) {
        this.$message.error('订单明细不能为空！')
        return false
      }
      var flag = true
      for (var data of this.itemData) {
        var key = data.key
        for (var field of this.needValidItemFields) {
          if (flag && !this.validateItemField(key, field, data[field])) {
            flag = false
          }
        }
      }
      return flag
    },
    /**
     * 提交表单
     */
    handleSubmit () {
      var flag = this.validateAllItemFields()
      const { form: { validateFields } } = this
      this.loading = true
      validateFields((errors, values) => {
        if (!errors) {
          values['deliveryTime'] = moment(values['deliveryTime']).format('YYYY-MM-DD')
          values['signDate'] = moment(values['signDate']).format('YYYY-MM-DD')
          for (const key in values) {
            if (typeof (values[key]) === 'object') {
              values[key] = JSON.stringify(values[key])
            }
          }
          if (this.selectCustomerValue === '') {
            this.$message.error('客户[' + values['customerId'] + ']不存在,请重新选择')
            this.loading = false
            return
          } else {
            values['customerId'] = this.selectCustomerValue
          }
          if (!flag) {
            this.loading = false
            return
          }
          values['itemList'] = this.itemData
          // console.log(values)
          saleOrderEdit(values).then((res) => {
            if (res.success) {
              this.$message.success('编辑成功')
              this.loading = false
              this.$emit('ok', values)
              this.handleCancel()
            } else {
              this.$message.error('编辑失败:' + res.message)
            }
          }).finally((res) => {
            this.loading = false
          })
        } else {
           this.loading = false
        }
      })
    },
    handleCancel () {
      this.code = ''
      this.form.resetFields()
      this.itemData = []
      this.selectCustomerValue = ''
      this.totalPrice = '0.00'
      this.totalTaxPrice = '0.00'
      this.taxRate = 1.0
      this.$multiTab.closeAndOpen('/saleOrder')
    }
  }
}
</script>

<style lang="less" scoped>
  .card{
    margin-bottom: 10px;
  }
  button {
    margin-right: 8px;
  }
</style>
